<?php
	session_start();

	$response;
	$userId;

	signUp();

	function signUp(){
		global $response;

		$userName = $_GET['userName'];

		unset($_SESSION['firstName']);

		$response = array(
			"success" => false,
			"userName" => '',
			"createdUser" => false,
			"storedEmail" => false,
			"storedPassword" => false,
			"storedUserInfo" => false,
			"createdDirectories" => false,
			"newUser" => true
		);

		$response['userName'] = $userName;

		if(createUser($userName)){
			$response['success'] = true;
			$response['createdUser'] = true;
			$_SESSION['userName']=$userName;
		}

		echo json_encode($response);
	}

	function createUser($userName){
		global $response, $userId;

		$userFile = fopen("../userInfo/users.txt", 'r+') or die("can't open user file");

		while(($buffer = fgets($userFile)) != false){
			$user = explode(",", $buffer);
			if($userName == $user[0]){
				$response['newUser'] = false;
				return false;
			}
		}

		$userId = uniqid();

		if(storeEmail()){
			$response['storedEmail'] = true;

			fwrite($userFile, $userName.", ".$userId."\n");
			fclose($userFile);
			return true;
		}
		else{
			return false;
		}

	}

	function storeEmail(){
		global $response, $userId;

		$email = $_GET['email'];

		$emailFile = fopen("../userInfo/email.txt", 'r+') or die("can't open email file");

		while(($buffer = fgets($emailFile)) != false){
			$storedEmail = explode(",", $buffer);
			if($email == $storedEmail[0]){
				$response['newUser'] = false;
				return false;
			}
		}

		if(storePassword()){
			$response['storedPassword'] = true;

			fwrite($emailFile, $email.", ".$userId."\n");
			fclose($emailFile);
			return true;
		}
		else{
			return false;
		}
	}

	function storePassword(){
		$password = $_GET['password'];

		global $response, $userId;

		$passwordFile = fopen("../userInfo/passwords.txt", 'a+') or die("can't open password file");

		if(storeUserInfo($userId)){
			$response['storedUserInfo'] = true;

			fwrite($passwordFile, $password.", ".$userId."\n");
			fclose($passwordFile);

			return true;
		}
		else{
			return false;
		}
	}

	function storeUserInfo($userId){
		$userInfoFile = fopen("../userInfo/info.txt", 'a+') or die("cant open user info file");

		if(makeDirectories()){
			$response['createdDirectories'] = true;

			fwrite($userInfoFile, ",,".$userId."\n");
			fclose($userInfoFile);

			return true;
		}
		else{
			return false;
		}
	}

	function makeDirectories(){
		global $response;

		$userDir = "../users/".$response['userName'];
		$defaultDir = $userDir."/default";

		if(mkdir($userDir, 0777)){
			if(mkdir($defaultDir, 0777)){
				return true;
			}
		}
		else{
			return false;
		}
	}

?>
